package cn.yto.print.utils;

import okhttp3.*;

import java.util.Map;
import java.util.Objects;

public class HttpRequestUtil {

    public static String sendPostRequest(String url, String jsonBody, Map<String, String> headers) throws Exception {
        OkHttpClient httpClient = new OkHttpClient();
        // 构建请求体
        RequestBody requestBody = RequestBody.create(jsonBody, MediaType.get("application/json; charset=utf-8"));
        Request.Builder requestBuilder = new Request.Builder().url(url).post(requestBody);
        if (null != headers) {
            headers.forEach(requestBuilder::header);
        }

        // 发送请求并获取响应
        Request request = requestBuilder.build();
        try (Response response = httpClient.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return Objects.requireNonNull(response.body()).string();
            } else {
                throw new Exception("Send Request Failed, Response Code：" + response.code());
            }
        }
    }

}
